<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <META  HTTP-EQUIV="Pragma" CONTENT="no-cache">
    <meta name="viewport" content="initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no,width=device-width" />
    <meta name="format-detection" content="telephone=no" />
    <meta name="app-mobile-web-app-capable" content="yes" />
    <meta name="app-mobile-web-app-status-bar-style" content="black-translucent" />
    <link rel="stylesheet" href="css/chat.css">
</head>
<body>
<div id="msgcontent" class='wrap flex'>
        
    <div id="contents" class='flex1' style="overflow: auto">
        
            
    </div>
    <div class="void">
        
    </div>
    <div class='bottom flex'>
        <input id="content" type="text" placeholder='' class='flex1'>
        
        <!-- <progress id="upd_progress" max="100" value="0"></progress> -->
        
                <input type="file" name="picpath" id="upd_pic" style="display: none;"
                    multiple="multiple" accept="image/*" />
                <input id="choose" type="button" value="+">
                <div id="send" class="msg_send">发送</div>
       
    </div>
   
</div>
<!-- <ul id="dowebok">
    <li><img src="http://p.qpic.cn/opensdk_im/0/8447307826376039917_0_2637CED64DDEA1D7C187A1A79D43C1B1/198" alt="图片1"></li>
</ul> -->



<script src="sdk/webim.js" type="text/javascript"></script>
<script src="js/lib/md5/spark-md5.js" type="text/javascript"></script>
<!--web im sdk 发送普通消息(文本和表情) api 示例代码-->
<!-- <script src="js/msg/upload_and_send_pic_msg.js" type="text/javascript"></script> -->
<script src="js/msg/send_common_msg.js" type="text/javascript"></script>
<script src="viewer-master/dist/viewer.js"></script>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script src="js/recentcontact/recent_contact_list_manager.js" type="text/javascript"></script>
<script src="js/msg/get_history_msg.js" type="text/javascript"></script>


<script type="text/javascript">
    let pictmp = [];
    let picid = 0;
    var timestamp_today = new Date(new Date().setHours(0,0,0,0)) / 1000 //今天00:00:00的时间戳


function scrollToEnd(){//滚动到底部
    var h = $(document).height()-$(window).height();
    $(document).scrollTop(h);
}
$("#content").click(function(){
		setTimeout(function(){
			document.getElementById("content").scrollintoview();// 参数可以是true， false, 空参数
		}, 300);
	    });
$(document).ready(function(){
//        document.body.scrollTop=document.body.scrollHeight;
        $("#send").click(function(){
            onSendMsg($("#content").val())          
            
            $("#content").val("");
            
        });
        $('.showImg').click(function(){$(this).hide()})
       

    });
    
    $('#choose').click(function(){

　　$('#upd_pic').trigger('click');

    });
    $("#upd_pic").change(function(){
        fileOnChange(this)
    // alert(this)
    });
    // $('#dowebok').viewer();
    function GetQueryString(name)
    {
        var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
       // var location_url = decodeURI(window.location)
        var r = decodeURI(window.location.search.substr(1)).match(reg);
        if(r!=null)return  unescape(r[2]); return null;
    }
    function bigpic(pic)
    {
           
            
    }
    function getTimeShow(today,action)
    {
        if(action == '发送中...')
        {
            return action;
        }
        var diff = action-today
        if( diff<= 86400 && diff >= 0)
        {
            return webim.Tool.formatTimeStamp(action,'hh:mm');
        }else if(diff < 0 && diff >= -86400)
        {
            return '昨天'+webim.Tool.formatTimeStamp(action,'hh:mm'); 
        }else{
            return webim.Tool.formatTimeStamp(action);
        }
    }
    function CreateText(ifself,name,content,time,headurl,type,type2)
    {
        if(ifself == 0)
        {
            var html = '<div id="tmppar'+picid+'" class="chat-content" > <div class="chat-content-list-time">'+getTimeShow(timestamp_today,time)+'</div> <div class="chat-content-list right"> <div class="chat-content-list-avatar "> <img src="'+headurl+'"></img>';
            html = html + '</div> <div class="chat-content-list-content"> <div class="chat-content-list-msg"> <div class="chat-content-list-msg-white"></div> <div class="chat-content-list-msg-gray"></div> <span>'+content+'</span>';
            html = html +  '</div> </div> </div> </div>';

        }else{
            var html = '<div id="tmppar'+picid+'" class="chat-content"> <div class="chat-content-list-time">'+getTimeShow(timestamp_today,time)+'</div> <div class="chat-content-list"> <div class="chat-content-list-avatar "> <img src="'+sessionStorage.getItem('other_face')+'"></img>';
            html = html + '</div> <div class="chat-content-list-content"> <div class="chat-content-list-msg"> <div class="chat-content-list-msg-white"></div> <div class="chat-content-list-msg-gray"></div> <span>'+content+'</span>';
            html = html +  '</div> </div> </div> </div>';
    
        }
            if(type == 1)
        {
            $("#contents").prepend(html);
        }
        else
        {
            $("#contents").append(html);
            
        }  
        if(type2 == 0)
        {
            return
        }
        picid++
        //发送接收消息 拉到底
        scrollToEnd()
    }
    function CreateImg(ifself,ifpic,bigpic,time,headurl,type,type2)
    {
        console.error(timestamp_today+','+time)

        if(ifself == 0)
        {
            //自己的消息
            var html = '<div id="tmppar'+picid+'" class="chat-content" > <div id="tmptime'+picid+'" class="chat-content-list-time">'+getTimeShow(timestamp_today,time)+'</div> <div class="chat-content-list right"> <div class="chat-content-list-avatar "> <img src="'+headurl+'"></img>';
            html = html + '</div> <div class="chat-content-list-content"> <div class="chat-content-list-msg-white"></div> <div class="chat-content-list-msg-gray"></div> <img id="tmppic'+picid+'" onclick="bigpic(\''+bigpic+'\')" style="width:250px;height:200px;"  src="'+ifpic+'">';
            html = html +  '</div> </div> </div>';   

        }else{
            //好友的消息
            var html = '<div id="tmppar'+picid+'" class="chat-content"> <div class="chat-content-list-time">'+getTimeShow(timestamp_today,time)+'</div> <div class="chat-content-list"> <div class="chat-content-list-avatar "> <img src="'+sessionStorage.getItem('other_face')+'"></img>';
            html = html + '</div> <div class="chat-content-list-content"> <div class="chat-content-list-msg-white"></div> <div class="chat-content-list-msg-gray"></div> <img onclick="bigpic(\''+bigpic+'\')" style="width:250px;height:200px;" src="'+ifpic+'">';
            html = html +  '</div> </div> </div>';          

        }
        if(type == 1)
        {
            $("#contents").prepend(html);
            
            //$("#contents").insertBefore(html,null)
        }
        else
        {
            $("#contents").append(html);
           
        }  
        if(type2 == 0)
        {
            //载入历史消息 不拉到底
            //$(document).scrollTop(100);
            return
        }
        //发送接收消息 拉到底
        picid++
        
        scrollToEnd()

    }
        

    //newMsgList 为新消息数组，结构为[Msg]
    //sessionStorage.setItem('chatwith','ceshi100');//将当前对话人存入session
    function onMsgNotify_chat(newMsgList) {
        webim.msgreaded();
        var sess, newMsg;
        for (var j in newMsgList) {//遍历新消息
            newMsg = newMsgList[j];
            var ID=newMsg.fromAccount;//用户标识
            var name = newMsg.fromAccountNick;//用户名
            var msgtype = newMsg.elems[0].type;
            
            var time = newMsg.time
            
            if(msgtype == 'TIMTextElem')
            {
                //文本消息
                var msgcontent = newMsg.elems[0].content.text;//内容
                if(sessionStorage.getItem('chatwith')==ID)
                {
                    CreateText(1,ID,msgcontent,time,sessionStorage.getItem('other_face'),0,1)
                }

            }
            else if(msgtype == 'TIMImageElem')
            {
                //图片消息
                var picurl = newMsg.elems[0].content.ImageInfoArray[0].url;
                if(sessionStorage.getItem('chatwith')==ID)
                {
                    console.error(time)
                    CreateImg(1,picurl,picurl,time,sessionStorage.getItem('other_face'),0,1)
                }
            }
            tmp = recentSessMap[ID];

        }
    }

    function changelistener()
    {
        var listeners = {
            "onMsgNotify": onMsgNotify_chat //监听新消息(私聊，普通群(非直播聊天室)消息，全员推送消息)事件，必填
            ,
            "onLongPullingNotify": function (data) {
                //console.debug('onLongPullingNotify', data)
            }
        };
        webim.changelistener(listeners , function(x){console.log(x)},function(x){console.error(x)});
    }


     /**
     * 上拉加载更多
     */
     var total = 1,//分页总数
        loading = false; //分页开关

    var LoadingDataFn = function (flag) {
        //var div_h = 0;
        // alert('loading...')
      
   
        getLastC2CHistoryMsgs(function(x){
            loading = true
            
            for(var i in x)
                {
                    fromid = x[i].fromAccount;
                    if(x[i].isSend)
                    {
                        if(x[i].elems[0].type == "TIMTextElem")
                        {
                            CreateText(0,fromid,x[i].elems[0].content.text,x[i].time,localStorage.getItem('self_face_url'),1,flag);    
                
                        }else if(x[i].elems[0].type == "TIMImageElem"){
                            CreateImg(0,x[i].elems[0].content.ImageInfoArray[2].url,x[i].elems[0].content.ImageInfoArray[0].url,x[i].time,localStorage.getItem('self_face_url'),1,flag); 
                    
                        }                  
                    }else{
                        if(x[i].elems[0].type == "TIMTextElem")
                        {
                            CreateText(1,fromid,x[i].elems[0].content.text,x[i].time,localStorage.getItem('self_face_url'),1,flag);   
                         
                        }else if(x[i].elems[0].type == "TIMImageElem"){
                            CreateImg(1,x[i].elems[0].content.ImageInfoArray[0].url,x[i].elems[0].content.ImageInfoArray[0].url,x[i].time,localStorage.getItem('self_face_url'),1,flag); 
                            
                        }
                    }
                }
            }
            ,function(e){
                console.error(e)
            });
         
           // $(document).scrollTop(div_h);

    };
    $(window).scroll(function () {
   
        if (($(window).scrollTop() <300)) {
            if (parseInt(sessionStorage.getItem('msg_complete')) == 0 && loading) {
                loading = false   
                LoadingDataFn(0);
                return
            } 
                    
            
        }
    });






    //选择图片触发事件
    

function fileOnChange(uploadFile) {
    // alert('pic selected')

    if (!window.File || !window.FileList || !window.FileReader) {
        alert("您的浏览器不支持File Api");
        return;
    }

    var file = uploadFile.files[0];
    var fileSize = file.size;

    //先检查图片类型和大小
    if (!checkPic(uploadFile, fileSize)) {
        return;
    }
    
    

    //预览图片
    var reader = new FileReader();
    var tmp_pid = 0;
    // var preDiv = document.getElementById('previewPicDiv');
    reader.onload = (function(file) {
        return function(e) {
            console.error(e)
            CreateImg(0,this.result,this.result,'发送中...',localStorage.getItem('self_face_url'),2,1)

        };
    })(file);
    // //预览图片
     reader.readAsDataURL(file);
     uploadPic(file,picid)

}

function uploadPic(file,tmp_pid) {
    var businessType; //业务类型，1-发群图片，2-向好友发图片
    if (selType == webim.SESSION_TYPE.C2C) { //向好友发图片
        businessType = webim.UPLOAD_PIC_BUSSINESS_TYPE.C2C_MSG;
    } else if (selType == webim.SESSION_TYPE.GROUP) { //发群图片
        businessType = webim.UPLOAD_PIC_BUSSINESS_TYPE.GROUP_MSG;
    }
    //封装上传图片请求
    var opt = {
        'file': file, //图片对象
        //'onProgressCallBack': onProgressCallBack, //上传图片进度条回调函数
        //'abortButton': document.getElementById('upd_abort'), //停止上传图片按钮
        'To_Account': selToID, //接收者
        'businessType': businessType //业务类型
    };
    //上传图片
    webim.uploadPic(opt,
        function(resp) {
            //上传成功发送图片
            sendPic(resp, file.name,tmp_pid);
        },
        function(err) {
            alert(err.ErrorInfo);
        }
    );
}
function sendPic(images, imgName,tmp_pid) {
    console.debug('sendPic', imgName);
    if (!selToID) {
        alert("您还没有好友，暂不能聊天");
        return;
    }

    if (!selSess) {
        var selSess = new webim.Session(selType, selToID, selToID, 0, Math.round(new Date().getTime() / 1000));
    }
    var msg = new webim.Msg(selSess, true, -1, -1, -1, sessionStorage.getItem('login_identifier'), 0, sessionStorage.getItem('login_identifier'));

    console.debug(imgName.split(".")[1]);
    var images_obj = new webim.Msg.Elem.Images(images.File_UUID, imgName.split(".")[1]);
    for (var i in images.URL_INFO) {
        var img = images.URL_INFO[i];
        var newImg;
        var type;
        switch (img.PIC_TYPE) {
            case 1: //原图
                type = 1; //原图
                break;
            case 2: //小图（缩略图）
                type = 3; //小图
                break;
            case 4: //大图
                type = 2; //大图
                break;
        }
        newImg = new webim.Msg.Elem.Images.Image(type, img.PIC_Size, img.PIC_Width, img.PIC_Height, img.DownUrl);
        images_obj.addImage(newImg);
    }
    msg.addImage(images_obj);
    //调用发送图片消息接口
    webim.sendMsg(msg, function(resp) {
        if (selType == webim.SESSION_TYPE.C2C) { //私聊时，在聊天窗口手动添加一条发的消息，群聊时，长轮询接口会返回自己发的消息   
        $('#tmppic'+tmp_pid).attr("onclick","bigpic(\'"+msg.elems[0].content.ImageInfoArray[0].url+"\');");
        $('#tmppic'+tmp_pid).attr('src',msg.elems[0].content.ImageInfoArray[1].url);
        $('#tmptime'+tmp_pid).html(getTimeShow(timestamp_today,msg.time))        
        }
        var data={
            'cus_im_id' : sessionStorage.getItem('chatwith'),
            'store_id' : sessionStorage.getItem('self_store_id'),
            'msg' : '[图片]',
            'send_people':localStorage.getItem('self_name_'),
            'self_im_id' : sessionStorage.getItem('login_identifier'),
        }
        $.ajax({url:"https://qyim.ec51.com/v1/check/send-xcx-msg",type:"POST",data:data,success:function(result){
            console.error(result)
                    
            }});
        
    }, function(err) {
        $("#tmppar"+tmp_pid).remove();
        if(err.ErrorCode == 20003)
        {
        var data={
            'cus_im_id' : sessionStorage.getItem('chatwith')
        }
        $.ajax({url:"https://qyim.ec51.com/v1/check/register-cus",type:"POST",data:data,success:function(result){
            
                    
            }});}
        alert('发送失败,请重试');
        //alert(err.ErrorInfo);
    });
}
//检查文件类型和大小

function checkPic(obj, fileSize) {
    var picExts = 'jpg|jpeg|png|bmp|gif|webp';
    var photoExt = obj.value.substr(obj.value.lastIndexOf(".") + 1).toLowerCase(); //获得文件后缀名
    var pos = picExts.indexOf(photoExt);
    if (pos < 0) {
        alert("您选中的文件不是图片，请重新选择");
        return false;
    }
    fileSize = Math.round(fileSize / 1024 * 100) / 100; //单位为KB
    if (fileSize > 30 * 1024) {
        alert("您选择的图片大小超过限制(最大为30M)，请重新选择");
        return false;
    }
    return true;
}




























    window.onload =function()
    {
        
        sessionStorage.setItem('other_face',GetQueryString('face'))
        sessionStorage.setItem('other_name',GetQueryString('name'))
        sessionStorage.setItem('MsgKey','')
        sessionStorage.setItem('LastMsgTime',0)

        $(document).attr("title",sessionStorage.getItem('other_name'));
        webim.msgreaded();

        //进入该页面首先拉取最近联系人,并创建html样式
        //然后更换监听
        var loginInfo_identifier = sessionStorage.getItem('login_identifier');
        changelistener();
        LoadingDataFn(1)
    }

</script>




</body>
</html>